package me.linzh;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * NIO demo
 * Created by leolin on 15/12/31.
 */
public class NioClient {

    private String host = "127.0.0.1";
    private int port;
    protected SocketChannel socketChannel;
    protected Selector selector;
//    protected


    private SelectedKeyHandler conncetHandler = new SelectedKeyHandler() {
        @Override
        public void handle(SelectionKey key) {
            SocketChannel sc = (SocketChannel) key.channel();
            try {
                sc.configureBlocking(false);
                sc.finishConnect();
                sc.register(selector, SelectionKey.OP_READ);
                System.out.println("connected");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    };
    private SelectedKeyHandler writeHandler = new SelectedKeyHandler() {
        @Override
        public void handle(SelectionKey key) {
            SocketChannel socketChannel = (SocketChannel) key.channel();
            ByteBuffer buffer = ByteBuffer.wrap("hello".getBytes());
            try {
                while (buffer.hasRemaining()) {
                    socketChannel.write(buffer);
                }
                System.out.println("writed");

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    };

    private NioClient() {
    }

    public NioClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public NioClient(int port) {
        this.port = port;
    }

    public void start() {
        try {
            socketChannel = SocketChannel.open();
            socketChannel.configureBlocking(false);
            selector = Selector.open();
            InetSocketAddress address = new InetSocketAddress(host, port);
            socketChannel.connect(address);
            socketChannel.register(selector, SelectionKey.OP_CONNECT);
            ReactorTask reactorTask = new ReactorTask(selector);
            reactorTask.setConnectHandler(conncetHandler);
            reactorTask.setWriteHandler(writeHandler);
            new Thread(reactorTask).run();
            Thread.currentThread().join();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        new NioClient("127.0.0.1", 2333).start();
    }
}


